package com.sun.showcase.biz.basic.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sun.showcase.biz.basic.dao.RoleGroupDao;
import com.sun.showcase.biz.basic.service.RoleGroupService;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.client.basic.domain.RoleGroup;
import com.sun.showcase.client.basic.query.RoleGroupQuery;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
@Service("roleGroupService")
@Transactional
public class RoleGroupServiceImpl implements RoleGroupService {

	@Autowired
	private RoleGroupDao roleGroupDao;

	public DataGrid datagrid(RoleGroupQuery roleGroupQuery) {
		DataGrid j = new DataGrid();
		Pager<RoleGroup> pager  = find(roleGroupQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private List<RoleGroupQuery> getQuerysFromEntitys(List<RoleGroup> roleGroups) {
		List<RoleGroupQuery> roleGroupQuerys = new ArrayList<RoleGroupQuery>();
		if (roleGroups != null && roleGroups.size() > 0) {
			for (RoleGroup tb : roleGroups) {
				RoleGroupQuery b = new RoleGroupQuery();
				BeanUtils.copyProperties(tb, b);
				roleGroupQuerys.add(b);
			}
		}
		return roleGroupQuerys;
	}

	private Pager<RoleGroup> find(RoleGroupQuery roleGroupQuery) {
		Page<RoleGroup> page = PageHelper.startPage(roleGroupQuery.getPage().intValue(), roleGroupQuery.getRows().intValue());
		
		List<RoleGroup> list = roleGroupDao.findPage(roleGroupQuery);
		Pager<RoleGroup> pager = new Pager<RoleGroup>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return pager;
		
	}
	


	public RoleGroup add(RoleGroupQuery roleGroupQuery) {
		RoleGroup t = new RoleGroup();
		BeanUtils.copyProperties(roleGroupQuery, t);
		roleGroupDao.save(t);
		roleGroupQuery.setRoleId(t.getRoleId());
		return t;
		
	}

	public void update(RoleGroupQuery roleGroupQuery) {
		RoleGroup t = roleGroupDao.getById(roleGroupQuery.getRoleId());
	    if(t != null) {
	    	BeanUtils.copyProperties(roleGroupQuery, t);
		}
	    roleGroupDao.update(t);
	}

	public void delete(RoleGroupQuery roleGroupQuery) {
		if (roleGroupQuery != null) {
			roleGroupDao.delete(roleGroupQuery);
		}
	}

	public RoleGroup get(RoleGroupQuery roleGroupQuery) {
		return roleGroupDao.getById(roleGroupQuery);
	}

	public RoleGroup get(String id) {
		return roleGroupDao.getById(id);
	}

	
	public List<RoleGroupQuery> listAll(RoleGroupQuery roleGroupQuery) {
	    List<RoleGroup> list = roleGroupDao.findList(roleGroupQuery);
		List<RoleGroupQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}

}
